<template>
    <el-row class="margin-tp custom-table_01" ref="exportPdf">
        <el-col :span="24" class="transf-title" style="margin-bottom:20px" v-if="istype == 1">打印四性检测报告</el-col>
        <el-table :data="tableData" border  :span-method="tableSpanMethod" style="margin:0 auto;" v-loading="loading" >
            <el-table-column align="center" prop="index1" label="" width="100%"></el-table-column>
            <el-table-column align="center" prop="index2" label=""  width="100%"></el-table-column>
            <el-table-column align="center" prop="index3" label="检测项目"  width="100%"></el-table-column>
            <!-- <el-table-column label="检测配置" width="350px" align="center" header-align="center"
                            prop="configuration" v-if="isShow == '1'">
                            <template slot-scope="scope">
                                <el-checkbox v-model="scope.row.configuration.isDetection == '0'"
                                    @change="handleDetectionChange(scope.row.configuration)">不检测</el-checkbox>
                                <el-checkbox v-model="scope.row.configuration.isPass == '1'"
                                    @change="handlePassChange(scope.row.configuration)">默认通过</el-checkbox>
                            </template>
                        </el-table-column> -->
            <!-- 检测方式   isPass==0   自动检测    1 默认通过 -->
            <!-- 检测结果   如果检测不通过    “” +条数；  -->
            <el-table-column label="检测方式" align="center" width="150%"  header-align="center" prop="configuration"
                v-if="isShow == '2'">
                <template slot-scope="scope">
                    <span  type="text" v-if="scope.row.configuration.isPass == '0'">自动检测</span>
                    <span  type="text" v-else>默认通过</span>
                </template>
            </el-table-column>
            <el-table-column label="检测结果" width="100%"  align="center" header-align="center" prop="configuration"
                v-if="isShow == '2'">
                <template slot-scope="scope">
                    <span  type="text" v-if="scope.row.configuration.detectionResult == '1'"
                        v-show="scope.row.configuration.detectionResult == '1'">通过</span>
                    <el-button  type="text" v-show="scope.row.configuration.detectionResult == '0'"
                                v-else-if="scope.row.configuration.detectionResult == '0' && scope.row.dId == '1224'"
                        @click="handleFail(scope.row.configuration)">不通过</el-button>
                    <el-button  type="text" v-show="scope.row.configuration.detectionResult == '0'" v-else
                        @click="handleFail(scope.row.configuration)">不通过{{ scope.row.configuration.failNum
                        }}条</el-button>
                </template>
            </el-table-column>

            <el-table-column label="检测时间" width="100%"  align="center" header-align="center" prop="configuration"
                v-if="isShow == '2'">
                <template slot-scope="scope">
                    <span>{{ scope.row.configuration.detectionTime }}</span>
                </template>
            </el-table-column>
        </el-table>

        <div class="transbz" v-if="istype == 1">
            <p>注：本表一式两份，档案移交单位和档案馆各持一份。</p>
        </div>
        <FailList :open="failOpen" ref="failRef" @cancel="cancel"></FailList>
    </el-row>
</template>
<script>
import FailList from "@/views/archive/fourNatures/detectionPlan/failList";
export default {
    props: ["istype", 'form', 'formINFO','sxjcId'],
    components: {
        FailList
    },
    data() {
        return {
            isShow: "2",
            configurationInfo: [],
            tableData: [],
            failOpen: false,
            loading:true
        }
    },
    watch: {
        form: {
            handler(valNew) {

                this.getTableData(valNew)
            },
            immediate: true
        }
    },
    methods: {
        // 不通过
        handleFail(configuration) {
            console.log(configuration,this.formINFO,this.sxjcId,"____")
            this.failOpen = true
            if(this.formINFO!=undefined){
                this.$nextTick(() => {
                this.$refs.failRef.init(configuration.dId, this.formINFO.sxId)
            })
            }else{

                this.$nextTick(() => {
                this.$refs.failRef.init(configuration.dId, this.sxjcId)
            })
            }

        },
        cancel() {
            this.failOpen = false
        },
        getTableData(data) {

            let lastChildNode = this.getLastChildNode(JSON.parse(JSON.stringify(data)));
            // 需要一个有且只有一个根节点的数据（如果返回的数据有且只有一个根节点，可省略此步骤）
            let obj = {
                id: '',
                pId: '',
                label: '',
                children: data // 删除 最后一级节点
            }
            // 将 树结构数据 格式化为二维数组
            let formatArr = this.parseTreeToRow(obj);
            // console.log(formatArr)

            // 再将其格式化为一维数组(ElementUi 表格所需要的数据格式)
            let tableData = [];
            if (formatArr[0].length != 0) {
                formatArr.map((item, index) => {
                    let pushObj = { number: index + 1 }; // 添加索引值（列 序号），如不需要，则设置为空对象
                    item.map((itemb, indexb) => {
                        // 动态添加 指标列数据 对应 表头 prop 属性值
                        pushObj['index' + (indexb + 1)] = itemb.label;
                        // 添加 表格行数据 id (取的是最后一个children的 id 值)
                        if (indexb == item.length - 1) {
                            pushObj.id = itemb.id;
                        };
                    });
                    tableData.push(pushObj)
                });
            }
            // console.log(tableData)

            // 获取树结构最深层级数
            this.getMaxFloorNum = this.getMaxFloor(data);

            // 未达到最深层级数节点 补充数据空缺
            for (let i = 0; i < tableData.length; i++) {
                for (let j = 0; j < this.getMaxFloorNum; j++) {
                    if (tableData[i]['index' + (j + 1)] == undefined) {
                        tableData[i]['index' + (j + 1)] = tableData[i]['index' + j];
                    }
                }
            }
            // 将抽离的最后一级节点 插入到 一维数组
            tableData.map((item, index) => {
                item.configuration = lastChildNode[index]
            });
            this.tableData = tableData;

            for (let i = 0; i < this.tableData.length; i++) {
                this.configurationInfo.push(JSON.parse(JSON.stringify(this.tableData[i].configuration)));
            }
            if(this.tableData.length>0){
                this.loading=false
            }

            // console.log(this.tableData, "+++++")

        },

        /**
        * 合并行或列的计算方法
        */
        tableSpanMethod({ row, column, rowIndex, columnIndex }) {
            return {
                rowspan: this.mergeRows(row[column.property], this.tableData, rowIndex, column.property),
                colspan: columnIndex > 0 ? this.mergeCells(row[column.property], row, column.property, this.getMaxFloorNum) : 1
            };
        },
        /**
            * 递归-----取出树组件最后子节点
            * @param {Object} node      树的源数据
            * @returns {Object} temp    取出树组件最后子节点的集合
            */
        getLastChildNode(node, temp = []) {
            let forFn = (arr) => {
                for (let i = 0; i < arr.length; i++) {
                    if (!arr[i].children || arr[i].children.length == 0) {
                        temp.push(...arr);
                        arr = [];
                    } else {
                        forFn(arr[i].children)
                    }
                }
            }
            forFn(node)
            return temp;
        },
        /**
         * 递归-----删除树组件源数据的最后子节点
         * @param {Object} node      树的源数据
         * @returns {Object} node    删除最后子节点之后的树的数据
         */
        deleteSourceNode(node) {
            for (let i = node.length - 1; i >= 0; i--) {
                if (!node[i].hasOwnProperty('children')) {
                    continue;
                }
                if (!node[i].children || node[i].children.length == 0) {
                    node.splice(i, 1);
                    continue;
                }
                this.deleteSourceNode(node[i].children);
            }
            return node;
        },
        /**
         * 递归-----将树结构数据格式，转化为 二维数组 表格形式
         * @param node  树的源数据
         * @param data  树转化为二维数组的数据
         * @param row   临时存储数据
         * @returns {*[]}
         */
        parseTreeToRow(node, data = [], row = []) {
            if (!node.children || node.children.length == 0) {
                data.push(row);
            } else {
                node.children.map((item, index) => {
                    const obj = {
                        id: item.dId,
                        pId: item.superId,
                        label: item.dName,
                        children: item.children
                    };
                    this.parseTreeToRow(item, data, [...row, obj]);
                });
            }
            return data;
        },
        /**
         * 递归-----树形数据（数组）获取最深层级数
         * @param {Object} treeData    树的源数据
         * @returns {Number}           最深层级数的值
         */
        getMaxFloor(treeData) {
            let floor = 0;
            let max = 0;
            let deepEach = (data, floor) => {
                data.map((item, index) => {
                    item.floor = floor;
                    if (floor > max) {
                        max = floor;
                    };
                    if (item.children && item.children.length != 0) {
                        deepEach(item.children, floor + 1);
                    };
                });
            };
            deepEach(treeData, 1);
            return max;
        },
        /**
         * 表格单元格合并-----行
         * @param {Object} value      当前单元格的值
         * @param {Object} data       当前表格所有数据
         * @param {Object} index      当前单元格的值所在 行 索引
         * @param {Object} property   当前列的property
         * @returns {number}          待合并单元格数量
         */
        mergeRows(value, data, index, property) {
            // 判断 当前行的该列数据 与 上一行的该列数据 是否相等
            if (index !== 0 && value === data[index - 1][property]) {
                // 返回 0 使表格被跨 行 的那个单元格不会渲染
                return 0;
            };

            // 判断 当前行的该列数据 与 下一行的该列数据 是否相等
            let rowSpan = 1;
            for (let i = index + 1; i < data.length; i++) {
                if (value !== data[i][property]) {
                    break;
                };
                rowSpan++;
            };
            return rowSpan;
        },
        /**
         * 表格单元格合并-----列
         * @param {Object} value      当前单元格的值
         * @param {Object} row        当前行数据
         * @param {Object} property   当前列的property
         * @param {Object} floorNum   二级指标的层级数
         * @returns {number}          待合并单元格数量
         */
        mergeCells(value, row, property, floorNum) {
            if (property != undefined) {
                // 取出当前 property 的尾数的 数字值
                let index = Number(property.substring(5));
                // 判断 当前行的该列数据 与 上一列数据 是否相等 (由于 “一级指标” 列不参与跨列，“二级指标” 列开始参与跨列，所以判断 property !== 'index2')
                if (property !== 'index2' && value === row['index' + (index - 1)]) {
                    // 返回 0 使表格被跨 列 的那个单元格不会渲染
                    return 0;
                }

                // 判断当前行的该列数据 与 下一列数据 是否相等
                let colSpan = 1;
                for (let i = index; i < floorNum; i++) {
                    if (value !== row['index' + (index + 1)]) {
                        break;
                    }
                    colSpan++;
                }
                return colSpan;
            } else {
                return 1;
            }
        },
    }
}
</script>
<style lang="scss" scoped>
::v-deep table{
    width: 100%!important;
    margin:0 auto;
}

::v-deep .el-dialog__body {
    padding: 0 20px 10px !important;
}

.steps-action {
    margin-top: 24px;
}

.printMain {
    display: flex;
    flex-direction: row;
}

::v-deep .el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: calc(100% - 30px);
    max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
    flex: 1;
    overflow: auto;
}



.orderBorder {
    width: 60%;
    margin: 0px auto;
}

.orderBorder td {
    height: 42px;
    line-height: 42px;
    text-align: center;
    border: rgb(42, 41, 41) 1px solid;
}

.transbz {
    width: 100%;
    margin: 0 auto;
    text-align: center;
}

::v-deep .orderBorder input {
    border: 0 !important;
    width: 100%
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
}

::v-deep input[type="number"] {
    -moz-appearance: textfield;
}

.transf-title {
    text-align: center;
    line-height: 55px;
    font-weight: bold;
    font-size: 28px;
}

.ymd {
    padding: 0;
    margin: 0;
    display: flex;
    width: 80%;
    text-align: right;
}

::v-deep .textNSME input {
    text-align: right !important;
}

.pinput {
    display: flex;
    flex-direction: row;
    line-height: 42px;
    align-items: center;
}



</style>
